package com.hanliy.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * @author hanyulin
 * @apiNote
 * @date 2021/11/6 13:44
 */
@Controller
public class AdminController {

    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @GetMapping({"/","/index"})
    public String index(Model model){
        model.addAttribute("msg","hello");
        return "index";
    }

    @GetMapping("/admin/add")
    public String add(){
        return "admin/add";
    }

    @GetMapping("/admin/update")
    public String update(){
        return "admin/update";
    }

    @PostMapping("/login")
    public String login(String username, String password, Model model){
        // 获取当前的用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登录信息
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try{
            // 执行登录请求：数据库的校验在reaml的认证里面
            subject.login(token);
            return "index";
        }catch (UnknownAccountException uae){
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException ice){
            model.addAttribute("msg","密码错误");
            return "login";
        }catch (AuthenticationException ae){
            model.addAttribute("msg","认证失败");
            return "login";
        }
    }

    @GetMapping("/403")
    public String unAuthorized(){
        return "403";
    }


}
